package com.csq.aop;

import com.csq.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ercai
 * @date 2019/7/25 - 10:03
 */
public class LogHandler implements InvocationHandler {

    //1.要代理的目标类
    private Object targetObject;

    //2.生成代理对象
    public Object newProxyInstance(Object object){

        this.targetObject = object;

        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
                targetObject.getClass().getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


        Object ret = null;
        //代理前
        System.out.println("代理前");
        //代理目标的参数
        User user = (User) args[0];
        if(StringUtils.isEmpty(user.getUserName())){
            method.invoke(targetObject,args);
        } else {
            System.out.println(user.toString()+"参数为空");
        }

        //代理后
        System.out.println("代理后");

        return ret;
    }
}
